﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using WZN_VoteSys.Models.Database;
using WZN_VoteSys.service;

namespace WZN_VoteSys.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class VoteController : ControllerBase
    {
        private readonly IJWTService _jwtService;
        private readonly WZN_VoteSysContext _db;
        public VoteController(IJWTService jwtService, WZN_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }


        /// <summary>
        /// 投票接口（需授权） 输入：投票项目Id 输出：投票结果消息
        /// </summary>
        /// <param name="entryID"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public string VoteUpdate(int entryID)
        {
            var Email = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var entry = _db.Entrys.FirstOrDefault(x => x.EntryId == entryID);
            if (entry == null)
            {
                return "改投票不存在";
            }
            var todayVoteCount = _db.VoteLists.Count(x => x.Email == Email && DateTime.ParseExact(x.VoteTime, "MM dd yyyy h:mmtt", CultureInfo.InvariantCulture).Date == DateTime.Today);
            if (todayVoteCount >= 5)
            {
                return "您今天投票次数已经到达上限";
            }
            //var count =_db.VoteLists
            //    .Where(x=>x.Email== Email&&x.EntyId==entryID)
            //    .Count();
            //if (count >= 5)
            //{
            //    return "您已经对改企业改分类投过五次票了";
            //}
            VoteList vote = new VoteList();
            vote.Email = Email;
            vote.EntyId = entryID;
            _db.VoteLists.Add(vote);
            if (_db.SaveChanges() > 0)
            {
                return "投票成功";
            }
            else
            {
                return "投票失败";
            }
        }



        /// <summary>
        /// 获取投票项目列表接口 输入：类别、搜索关键字、分页信息 输出：所需展示内容信息
        /// </summary>
        /// <param name="Classid"></param>
        /// <param name="seacher"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult VoteList(int Classid,string seacher,int page)
        {
            if (Classid == 0)
            {
                return NotFound();
            }
            if(seacher!= null)
            {
                //_db.Enterprises.Where(x => x.Enterprisename.Contains(seacher)).Join(_db.Entrys, x => x.EnterpriseId, y => y.EnterpriseId, (x, y) => new
                //{

                //});

                var temp = from Entry in _db.Entrys
                           join enterprise in _db.Enterprises on Entry.EnterpriseId equals enterprise.EnterpriseId
                           join vote in _db.VoteLists on Entry.EntryId equals vote.EntyId into voteGroup
                           where enterprise.Enterprisename.Contains(seacher)&&Entry.Classid == Classid
                           select new
                           {
                               Enterprisename = enterprise.Enterprisename,
                               votecount=voteGroup.Count()
                           };
                var totalCount=temp.Count();
                var skip = 0;
                var take = 0;
                if (page < 1)
                {
                    page = 1;
                }
                var endPage = 0;
                if (totalCount % 6 != 0)
                {
                    endPage = totalCount / 6 + 1;
                }
                else
                {
                    endPage = totalCount / 6;
                }
                if (endPage == 1)
                {
                    skip = 1;
                    take = totalCount;
                }
                if (page > endPage)
                {
                    page = endPage;
                    skip = page * 6 - 5;
                    take = totalCount;
                }
                else
                {
                    skip = page * 6 - 6;
                    take = page * 6;
                }
                return Ok(temp.Skip(skip).Take(take).ToList());

            }


            else
            {
                var temp = from Entry in _db.Entrys
                           join enterprise in _db.Enterprises on Entry.EnterpriseId equals enterprise.EnterpriseId
                           join vote in _db.VoteLists on Entry.EntryId equals vote.EntyId into voteGroup
                           where Entry.Classid == Classid
                           select new
                           {
                               Enterprisename = enterprise.Enterprisename,
                               votecount = voteGroup.Count()
                           };
                var totalCount = temp.Count();
                var skip = 0;
                var take = 0;
                if (page < 1)
                {
                    page = 1;
                }
                var endPage = 0;
                if (totalCount % 6 != 0)
                {
                    endPage = totalCount / 6 + 1;
                }
                else
                {
                    endPage = totalCount / 6;
                }
                if (endPage == 1)
                {
                    skip = 1;
                    take = totalCount;
                }
                if (page > endPage)
                {
                    page = endPage;
                    skip = page * 6 - 5;
                    take = totalCount;
                }
                else
                {
                    skip = page * 6 - 6;
                    take = page * 6;
                }
                return Ok(temp.Skip(skip).Take(take).ToList());
            }
        }




    }
}
